import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { WsAdapter } from '@nestjs/platform-ws';
import * as cors from 'cors';
import { join } from 'path';
import * as serveStatic from 'serve-static';
import { ValidationPipe } from './common/validation.pipe';
const bodyParser = require("body-parser");
import {schedule} from './common/schedule';
require("body-parser-xml")(bodyParser);
const pord = process.env.NODE_ENV == 'production' ? 3000 : 3001;
const prefix  = process.env.NODE_ENV == 'production' ? 'api' : 'apitest';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.useWebSocketAdapter(new WsAdapter(app));
  app.setGlobalPrefix(prefix);
  app.use(cors({
    origin:['*'],
    credentials:true
  }));
  app.use('/public', serveStatic(join(__dirname, './public'), {
    extensions: ['jpg', 'jpeg', 'png', 'gif','*'],
  }));
  app.use(bodyParser.xml({
    limit: "1MB",   // Reject payload bigger than 1 MB
    xmlParseOptions: {
      normalize: true,     // Trim whitespace inside text nodes
      normalizeTags: true, // Transform tags to lowercase
      explicitArray: false // Only put nodes in array if >1
    },
    verify: function(req, res, buf, encoding) {
      if(buf && buf.length) {
        // Store the raw XML
        req.rawBody = buf.toString(encoding || "utf8");
      }
    }
  }));
  app.use(bodyParser.json());
  app.useGlobalPipes(new ValidationPipe());
  schedule();
  await app.listen(pord);
}
bootstrap()